package com.wb.controller;

import com.wb.dao.BlogMapper;
import com.wb.dao.LikesMapper;
import com.wb.dao.PictureMapper;
import com.wb.dao.UserMapper;
import com.wb.entity.*;
import com.wb.service.BlogService;
import com.wb.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class testController {
    SimpleUser simpleUser=new SimpleUser();
    UserService uservice = new UserService();
    BlogService blogService=new BlogService();
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-dao.xml");
    BlogMapper blogMapper = (BlogMapper) applicationContext.getBean("blogMapper");
    UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper");
    PictureMapper pictureMapper = (PictureMapper)applicationContext.getBean("pictureMapper");
    LikesMapper likesMapper = (LikesMapper) applicationContext.getBean("likesMapper");
    List<Blog> list;
    int user_id;
    @RequestMapping(value="/personblog")
    public ModelAndView personBlog(@RequestParam(value = "user_id")int user_id) {
        if(user_id==-1)//-1表示默认，即返回本人博客信息
        {
            this.user_id=SaveUserId.userId;
            return personBlog(SaveUserId.userId);
        }
        else
            this.user_id=user_id;
        ModelAndView mdv=new ModelAndView();
        mdv.addObject("user_id", user_id);
        mdv.setViewName("pb");
        if(user_id==0)//空指针返回自己的个人博客
        {
            user_id= SaveUserId.userId;
        }
        //准备用户名称和头像
        if(SaveUserId.userId==0) {
            mdv.addObject("photo", "/picture/user1.png");
            mdv.addObject("name", "匿名");

        }
        else {
            User user = uservice.userMessage(SaveUserId.userId);
            mdv.addObject("photo", user.getPhoto());
            mdv.addObject("name", user.getUser_name());
        }

        return mdv;
    }
    @RequestMapping(value="/result3")
    public ModelAndView result() {
        ModelAndView mdv = new ModelAndView();

        mdv.setViewName("index");
        return mdv;
    }

    @RequestMapping(value="/hello")
    public  String login()  {
        return "index";
    }
    @ResponseBody
    @RequestMapping(value="/test5")
    public  String test5(@RequestBody User user)  {
        System.out.println(user.getUser_id());
        return "index";
    }
    @RequestMapping(value="/test5", method = {RequestMethod.POST})
    @ResponseBody
    public User requestBodyBind(@RequestBody User user){
        System.out.println("requestbodybind:" + user);
        int id = user.getUser_id();
        User user1 =userMapper.getUserById(id);
        System.out.println(id);
        return user1;
    }
    // 后台接值方法
    @RequestMapping(value="/getBlogs")
    @ResponseBody
    public List<Blog> getBlogs(){
        list =blogMapper.getAllBlogs();
        for (Blog blog:list) {
            int a = blog.getUser_id();
            User user=userMapper.getUserById(a);
            blog.setUser_name(user.getUser_name());
            //获得头像
            if(user.getPhoto()==null){
                blog.setPhoto("picture/波斯猫.jpg");
            }else {
                blog.setPhoto(user.getPhoto());
            }
            int b=blogMapper.getLikesSum(blog);
            blog.setLikesum(b);
            int d=blogMapper.getCommentSum(blog);
            blog.setCommentsum(d);
            List<Comment> c = blogMapper.getCommentList(blog);
            blog.setComment(c);
            List<Picture> p = blogMapper.getPicList(blog);
            blog.setPic(p);
        }
        return list;
    }
    /* @RequestMapping(value="/personblog")
     public String personBlog(ModelMap model,@RequestParam(value = "user_id")int user_id) {
         model.addAttribute("user_id", user_id);
         return "test";
     }*/
    @RequestMapping(value="/getPersonBlogs")
    @ResponseBody
    public List<Blog> getPersonBlogs(@RequestParam(value = "user_id")int user_id){
        User mainuser = userMapper.getUserById(user_id);
        list = userMapper.getOnesBlogs(mainuser);
        for (Blog blog:list) {
            int a = blog.getUser_id();
            User user=userMapper.getUserById(a);
            blog.setUser_name(user.getUser_name());
            //获得头像
            if(user.getPhoto()==null){
                blog.setPhoto("picture/波斯猫.jpg");
            }else {
                blog.setPhoto(user.getPhoto());
            }
            int b=blogMapper.getLikesSum(blog);
            blog.setLikesum(b);
            int d=blogMapper.getCommentSum(blog);
            blog.setCommentsum(d);
            List<Comment> c = blogMapper.getCommentList(blog);
            blog.setComment(c);
            List<Picture> p = blogMapper.getPicList(blog);
            blog.setPic(p);
        }
        return list;}
    @RequestMapping(value="/updatePersonBlogs")
    @ResponseBody
    public List<Blog> updatePersonBlogs(@RequestParam(value = "user_id")int user_id,
                                        @RequestParam(value = "blog_id")int blog_id){
        Likes likes=new Likes();
        likes.setUser_id(SaveUserId.userId);
        likes.setBlog_id(blog_id);
        System.out.println("点赞哥点赞个===============================");
        BlogService blogService=new BlogService();
        blogService.addLike(likes);
        for(int i=0;i<list.size();i++)
        {
            Blog blog_comp=list.get(i);
            if(blog_comp.getUser_id()==blog_id)//找到啦qwq
            {
                list.get(i).setLikesum(blogMapper.getLikesSum(blog_comp));
            }
        }
        return list;}
    //暂时不提供多图功能以及user_id(隐藏表单域)，绑定才行 article为空返回并提示不可为空
    @RequestMapping("/poBlog")
    public ModelAndView poBlog(@RequestParam(value = "blogImage",required = false) MultipartFile file,
                               @RequestParam(value = "blogArticle",required = false)String article,
                               @RequestParam(value = "user_id")String id){
        Blog blog = new Blog();
        int uid = Integer.valueOf(id);
        blog.setUser_id(SaveUserId.userId);
        blog.setArticle(article);
        blogMapper.addBlog(blog);
        int currentId=blogMapper.getCurrentBID();
        Picture picture = new Picture();
        ModelAndView mv = new ModelAndView();
        mv.addObject("blogArticle",article);
        mv.addObject("user_id",id);

        if(file!=null) {
            //      获取Servlet的运行路径下的imgs文件夹作为上传图片的存储路径
            String uploadRootPath = "C:/picture/";
            System.out.println("uploadRootPath=" + uploadRootPath);

//      检查图片存储路径是否存在，如果不存在，创建路径
            File uploadRootDir = new File(uploadRootPath);
            if (!uploadRootDir.exists())
                uploadRootDir.mkdirs();
//      获取源文件的文件名
            String fileName = file.getOriginalFilename();
            mv.addObject("imgsrc","/picture/" + fileName);
//      创建目标文件，制定文件存储路径和文件名
            File targetFile = new File(uploadRootPath + fileName);
            if (fileName != null && fileName.length() > 0) {
                try {
//              将源文件转移到目标文件，使用transferTo方法
                    file.transferTo(targetFile);
                    picture.setPic_addr("/picture/" + fileName);
                    picture.setBlog_id(currentId);
                    pictureMapper.addPicture(picture);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        mv.setViewName("abc");
        return mv;
    }
    //由于返回的类需要有按钮类型和按钮message，所以把你的mainuser设置为我的simpleUser
    @RequestMapping(value="/getPersonalInfo")
    @ResponseBody
    public SimpleUser getPersonalInfo(@RequestParam(value = "user_id")int user_id){
        User mainuser = userMapper.getUserById(user_id);
        List<User> bindUser=blogService.getFollowing(userMapper.getUserById(SaveUserId.userId));//获取当前账户主动关注的人
        HashMap<Integer,String> findMap=new HashMap<>();
        for(int i = 0; i < bindUser.size(); i++)//用HashMap存储方便进行查找的数据结构
        {
            User u=bindUser.get(i);
            findMap.put(u.getUser_id(),u.getUser_name());
        }
        mainuser.setBlogSum(userMapper.getBlogSum(mainuser));//二层调用mainuser.user.blogsum
        mainuser.setFollowers(userMapper.getFollowerSum(mainuser));
        mainuser.setFollows(userMapper.getFollowSum(mainuser));
        simpleUser.setBlogSum(mainuser.getBlogSum());
        simpleUser.setUser(mainuser);
        System.out.println(findMap.size());
        if(findMap.size()==0||!findMap.containsKey(simpleUser.getUser().getUser_id())) {//当前用户没有关注对应的用户
            simpleUser.setStatus(true);
            simpleUser.setMessage("关注");
            simpleUser.setClasses("btn btn-success btn-sm");
        }
        else
        {
            simpleUser.setStatus(false);
            simpleUser.setMessage("已关注");
            simpleUser.setClasses("btn btn-default btn-sm");
        }
        simpleUser.setMethod("personBlog?user_id="+simpleUser.getUser().getUser_id());//跳转连接
        simpleUser.setIntroduction(mainuser.getIntroduction());//自我介绍
        simpleUser.setPicture(mainuser.getPhoto());//头像
        simpleUser.setFollowed(mainuser.getFollows());//粉丝数
        simpleUser.setUserName(mainuser.getUser_name());//用户名
        return simpleUser;
    }
    @RequestMapping(value="/updatePersonalInfo")
    @ResponseBody
    public SimpleUser updatePersonalInfo(@RequestParam(value = "status")String status){
        Bind bind=new Bind();
        bind.setUser_id(user_id);
        bind.setFollower_id(SaveUserId.userId);
        if(status.equals("true"))//true代表原来是绿色（还没关注要关注）
        {//自己不能关注自己
            if(simpleUser.getUser().getUser_id()==SaveUserId.userId)
                return simpleUser;
            simpleUser.setStatus(false);
            simpleUser.setMessage("已关注");
            simpleUser.setClasses("btn btn-default btn-sm");
            simpleUser.setFollowed(blogService.addBind(bind));
            simpleUser.getUser().setFollowers(simpleUser.getFollowed());
        }
        else//（已经关注要取消关注）
        {
            //取消关注
            simpleUser.setFollowed(blogService.deleteBind(bind));
            simpleUser.setStatus(true);
            simpleUser.setMessage("关注");
            simpleUser.setClasses("btn btn-success btn-sm");
            simpleUser.getUser().setFollowers(simpleUser.getFollowed());

        }
        System.out.println("我返回啦我返回啦");

        return simpleUser;
    }



}


